11. PropTypes
Type checking a Component's Props with PropTypes
As we implement additional features into our app, we may soon find ourselves debugging our components more frequently. For example, what if the props
that we pass to our components end up being an unintended data type (e.g. an object instead of an array)? PropTypes is a package that lets us define the data type we want to see right from the get-go and warn us during development if the prop that's passed to the component doesn't match what is expected.
To use PropTypes in our app, we need to install prop-types:
npm install --save prop-types
Alternatively, if you have been using yarn to manage packages, feel free to use it as well to install:
yarn add prop-types
Let's jump right in and see how it's used!
Add PropTypes Package To Verify ListContacts Props
Task Feedback:
Way to go!
QUESTION:
Consider this component:
import PropTypes from 'prop-types';
class Email extends React.Component {
render() {
return (
<h3>Message: {this.props.text}</h3>
);
}
}
Email.propTypes = {
text: // ???
};
We want to validate that a text
prop is indeed being passed in, and that its data type is a string. What should the value of the above object's text
key be?
SOLUTION:
These answers need to be solved by yourself, I believe you can do it
PropTypes Recap
All in all, PropTypes is a great way to validate intended data types in our React app. Type checking our data with PropTypes helps us identify these bugs during development to ensure a smooth experience for our app's users.
Further Research
- prop-types library from npm
- Typechecking With Proptypes from the React Docs